#include "pub_sub/publisher.h"
#include "pub_sub/pub_sub_infos.h"

template <typename MsgType>
Publisher<MsgType>::Publisher(const std::string &topic_name)
    : topic_name_(topic_name) {
  serializer_ = MsgSerializer<MsgType>();

  std::string queue_path = "/tmp/" + topic_name_ + "_Q";
  msgq_ = make_shared_msgq(queue_path);
  msgq_->init_publisher();
  
  PublisherInfo pub_info(topic_name_, std::static_pointer_cast<void>(msgq_));
  PubInfosManager::getInstance().registerPublisher(topic_name_, pub_info);
}

template <typename MsgType>
Publisher<MsgType>::~Publisher() {
  PubInfosManager::getInstance().unregisterPublisher(topic_name_);
}

template <typename MsgType>
bool Publisher<MsgType>::Publish(const MsgType &msg) {
  auto serialized_data = serializer_.Serialize(msg);
  bool result = msgq_->send(serialized_data);
  
  return result;
}

template <typename MsgType>
bool Publisher<MsgType>::Publish(const MsgPtr &msg) {
  if (!msg) {
    return false;
  }
  return Publish(*msg);
}
